<template>
	<view class="container">
		<view class="selected-all">
			<view class="drop-down-box" @click="btnShowHideClick()">
				<text class="dropdown-content">{{choiceContent||"选择配送方式"}}</text>
				<image class="dropdown-icon" :class="{select:isShowChoice}" src="/static/supermarket/icon_arrow.png"
					mode="widthFix"></image>
			</view>
			<!-- 弹框内容 -->
			<view class="dialog-view" v-if="isShowChoice">
				<text class="dialog-title" v-for="(item ,index) in choiceList" :key="index"
					@click="btnChoiceClick(index)">{{item.choiceItemContent}}</text>
			</view>
		</view>
		<view class="store-list">
			<view class="title">{{storeData.name}}</view>
			<view class="column" v-for="(item,index) in shoppCart" :key="index">
				<image class="left" :src="adminImgPath+item.image" mode="aspectFill"></image>
				<view class="center">
					<view class="name">{{item.name}}</view>
					<view class="num">X{{item.number}}</view>
				</view>
				<view class="right"><text>￥</text>{{item.total}}</view>
			</view>
			<view class="price-total">
				<view class="tag">价格合计</view>
				<view class="price"><text>￥</text>{{totalPrice}}</view>
			</view>
		</view>
		<!-- 跑腿运费 -->
		<view v-if="choiceIndex == 2" class="transportation_expenses">
			<view class="tile">
				运费
			</view>
			<view class="price">
				{{supermarket || 0}}元
			</view>
		</view>

		<view class="addRec-menu-o" v-if="choiceIndex == 2">
			<view class="ikz-form-input-box ikz-afters" @click="goaddress">
				<image class="ikz-form-input-img" src="/static/campus/shou.png"></image>
				<view v-if="!address_default">收货地点(必选)</view>
				<view class="ikz-form-address" v-else>
					{{address_default.name}}-{{address_default.mobile}}
					<view class="ikz-form-address-detail">
						{{address_default.group_name}}-{{address_default.detail}}
					</view>
				</view>
			</view>
		</view>
		<view class="addRec-menu-o" v-if="choiceIndex == 2">
			<view class="ikz-form-input-box ikz-afters">
				<image class="ikz-form-input-img" src="/static/campus/time.png"></image>
				<view style="width: 80%;">
					<ikz-datetime @returnTime="returnTime"></ikz-datetime>
				</view>
			</view>
		</view>

		<!-- 地址 -->
		<view class="remarks">
			<view class="title">备注信息</view>
			<textarea v-model="remarks" placeholder="请输入备注信息" placeholder-style="fontSize: 22rpx" />
		</view>
		<view class="btn-box">
			<view class="btn-box-left">
				<view class="priceBox">
					<view class="hx-color-white"><text>￥</text>{{totalPrice}}</view>
				</view>
			</view>
			<view class="btn-box-right" @click="createOrder()">
				<view class="jiesuan">立即支付</view>
			</view>
		</view>
	</view>
</template>

<script>
	import ikzDatetime from '@/pages/Component/Public/Pickertime/public/datetime/index.vue';
	import ikz from '@/pages/Common/tools.js';
	var app = getApp();
	import Vue from 'vue'
	export default {
		components: {
			ikzDatetime
		},
		data() {
			return {
				address_default: '', //地图
				id: 0,
				scrollData: {},
				//购物车缓存 Storage 名称
				shoppingCartStorageName: 'shopping_cart',
				//门店信息
				storeData: {},
				//购物车
				shoppCart: [],
				//头部选项卡 参数为 0不显示选项卡,1,2
				tabIndex: 1,
				//结算价
				totalPrice: 0,
				//已优惠价
				totalYhPrice: 0,
				//商品数量
				totalNumber: 0,
				remark: "",
				adminImgPath: app.globalData.adminImgPath,
				remarks: '',
				isShowChoice: false,
				choiceIndex: 0,
				choiceList: [{
						choiceItemContent: "到店自取",
						value: 1
					},
					{
						choiceItemContent: "送货上门",
						value: 2
					}
				],
				choiceContent: "",
				orderId: 0,
				orderNo: 0,

				group_name: '请选择收货地址',

				// 运费
				supermarket: 0,
				
				hope_arrive:"",
			}
		},
		watch: {
			choiceIndex(newV, oldV) {
				console.log(newV, oldV);
				if (newV == 1) {
					let cj = 0
					let op = 0
					let p = 0
					let num = 0
					let totalPrice = 0
					let totalNumber = 0
					let totalOldPrice = 0
					//计算总商品数量和总价
					for (var i in this.shoppCart) {
						this.shoppCart[i].total = Number(this.shoppCart[i].total).toFixed(2)
						p = Number(this.shoppCart[i].price);
						op = Number(this.shoppCart[i].oldprice);
						num = Number(this.shoppCart[i].number)
						totalNumber += num
						totalPrice += p * num
						if (op > p) {
							cj += (op - p) * num
						}
					}
					this.totalPrice = Number(totalPrice).toFixed(2)
					this.totalYhPrice = cj
					this.supermarket = 0
				} else if (newV == 2) {
					this.queryFreight()

				}
			}
		},
		onShow() {
			this.address_default = app.globalData.user_address.address_default;
		},
		onLoad(option) {
			if (option.id) {
				this.id = option.id
				let totalPrice = 0
				let totalNumber = 0
				let totalOldPrice = 0
				let carts = uni.getStorageSync(this.shoppingCartStorageName) || []
				if (carts) {
					//根据缓存数据 获取购物车中属于本商店的商品
					for (let i in carts) {
						if (carts[i].store_id == option.id) {
							this.shoppCart = carts[i].shopping_cart;
							this.storeData = carts[i]
							break;
						}
					}
				}
				let cj = 0
				let op = 0
				let p = 0
				let num = 0
				//计算总商品数量和总价
				for (var i in this.shoppCart) {
					this.shoppCart[i].total = Number(this.shoppCart[i].total).toFixed(2)
					p = Number(this.shoppCart[i].price);
					op = Number(this.shoppCart[i].oldprice);
					num = Number(this.shoppCart[i].number)
					totalNumber += num
					totalPrice += p * num
					if (op > p) {
						cj += (op - p) * num
					}
				}
				this.totalPrice = Number(totalPrice).toFixed(2)
				this.totalYhPrice = cj
			}

		},
		methods: {
			// 
			returnTime(e) {
				console.log(e);
				this.hope_arrive = e
			},
			//我的地址
			goaddress() {
				uni.navigateTo({
					url: '/pages/Component/Module/Address/Program/myAddress/index?type=' + '收货'
				})
			},
			geselectAddress() {
				var _that = this
				uni.chooseLocation({
					success: function(res) {
						_that.group_name = res.address + '-' + res.name
						console.log('位置名称：' + res.name);
						console.log('详细地址：' + res.address);
						console.log('纬度：' + res.latitude);
						console.log('经度：' + res.longitude);
					},
					fail(err) {
						console.log(err);
					}
				})
			},
			// 选择
			btnChoiceClick(index) {
				this.isShowChoice = false
				this.choiceContent = this.choiceList[index].choiceItemContent
				this.choiceIndex = this.choiceList[index].value
			},
			// 显示与隐藏选择内容
			btnShowHideClick() {
				if (this.isShowChoice) {
					this.isShowChoice = false
				} else {
					this.isShowChoice = true
				}
			},
			// 查询运费
			queryFreight() {
				var path = '/xyb/supermarket/Index/queryFreight';
				var data = {}
				ikz.post(path, data, res => {
					if (res.data.status == 200) {
						this.supermarket = res.data.data.supermarket
						this.totalPrice = Number(parseFloat(this.totalPrice) + parseFloat(Number(this.supermarket)
							.toFixed(2))).toFixed(2)
					}
				})
			},
			// 创建订单
			createOrder() {
				if(this.choiceIndex == 0){
					uni.showModal({
						showCancel: false,
						title: "提示",
						content: "请选择配送方式"
					})
					return
				}
				
				if(this.choiceIndex == 2 && this.hope_arrive == ''){
					uni.showModal({
						showCancel: false,
						title: "提示",
						content: "请选择送达时间"
					})
					return
				}
				
				if (this.address_default == '请选择收货地址' && this.choiceIndex == 2 ) {
					uni.showModal({
						showCancel: false,
						title: "提示",
						content: "请选择收货地址"
					})
					return
				}
				// if(this.orderId) {
				// 	this.payment()
				// 	return
				// }
				var goods_param = []
				for (var i = 0; i < this.shoppCart.length; i++) {
					let data = {
						goods_id: this.shoppCart[i].id,
						count: this.shoppCart[i].number,
						transportationExpenses: this.supermarket
					}
					goods_param.push(data)
				}
				var path = '/xyb/supermarket/order/create';
				var data = {
					goods_param: JSON.stringify(goods_param),
					delivery: this.choiceIndex, // 1商品自提 2商品代取
					remarks: this.remarks,
					mobile: this.address_default.mobile,
					hope_arrive: this.hope_arrive,
					group_name: this.address_default.group_name + "-" + this.address_default.detail,
				};
				ikz.post(path, data, res => {
					console.log("创建订单", res)
					if (res.data.code) {
						this.orderId = res.data.data.id
						this.orderNo = res.data.data.order_no
						let carts = uni.getStorageSync(this.shoppingCartStorageName)
						for (let i in carts) {
							if (carts[i].store_id == this.storeData.store_id) {
								carts.splice(i, 1)
								break;
							}
						}
						uni.setStorageSync(this.shoppingCartStorageName, carts)
						this.payment()
					} else {
						uni.showModal({
							title: '提示',
							content: res.data.msg,
							showCancel: false,
							success: function(res) {}
						});
					}
				})
			},
			// 调起小程序微信支付
			payment() {
				uni.showLoading({
					mask: true,
					title: '正在请求支付...'
				})
				var path = '/xyb/supermarket/order/wx_minapp_pay';
				var data = {
					order_no: this.orderNo,
				};
				ikz.post(path, data, res => {
					console.log("调起小程序微信支付 ", res)
					uni.hideLoading()
					if (res.data.code == 1) {
						wx.requestPayment({
							timeStamp: res.data.data.timeStamp,
							nonceStr: res.data.data.nonceStr,
							package: res.data.data.package,
							signType: res.data.data.signType,
							paySign: res.data.data.paySign,
							success: res => {
								console.log('success', res);
								if (res.errMsg == "requestPayment:ok") {
									uni.showToast({
										title: '支付成功',
										duration: 2000,
										icon: 'success'
									})
									uni.redirectTo({
										url: "/pages/Component/supermarket/Program/store/success?id=" +
											this.orderId + "&type=" + this.choiceIndex +
											"&address=" + this.storeData.address
									})
								}
							},
							fail: res => {
								console.log('fail', res);
								uni.showModal({
									title: "提示",
									showCancel: false,
									content: "订单已创建，请及时进行支付"
								})
							},
							complete: res => {
								console.log('complete', res);
							}
						})
					} else {
						uni.showToast({
							title: res.data.msg,
							icon: 'none'
						})
					}
				})
			},
		}
	}
</script>

<style lang="scss">
	page {
		background: #F6F7FB;
	}

	.ikz-form-input-img {
		width: 50rpx;
		height: 50rpx;
		margin-right: 10rpx;
	}

	.ikz-form-input-box {
		box-sizing: border-box;
		// padding: 30rpx;
		width: 95%;
		// margin: 30rpx auto 0;
		display: flex;
		align-items: center;
		background: #fff;
		border-radius: 15rpx;
	}

	.ikz-afters {
		position: relative;
	}

	.ikz-afters:after {
		content: " ";
		display: inline-block;
		height: 6px;
		width: 6px;
		border-width: 2px 2px 0 0;
		border-color: #888;
		border-style: solid;
		-webkit-transform: matrix(0.71, 0.71, -.71, 0.71, 0, 0);
		transform: matrix(0.71, 0.71, -.71, 0.71, 0, 0);
		top: -2px;
		position: absolute;
		top: 50%;
		margin-top: -4px;
		right: -9px;
	}

	.addRec-menu-o {
		background: #FFFFFF;
		border-radius: 9rpx;
		// padding: 29rpx;
		margin-top: 20rpx;
		font-family: Arial, Helvetica, sans-serif;
		font-size: 36rpx;
		// border-bottom: 1px solid #eee;
	}

	.addRec-menu-o-left {
		line-height: 60rpx;
		width: 20%;
	}

	.addRec-menu-o-left {
		line-height: 60rpx;
		width: 20%;
	}

	.addRec-menu-o {
		display: flex;
		flex-direction: row;
		justify-content: space-between;
		padding: 20rpx;
		font-size: 30rpx;
	}

	.addRec-menu-o-right {
		width: 70%;
		color: gainsboro;
		font-size: 30rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.addRec-menu-o-right input {
		height: 70rpx;
		color: black;
	}


	.ikz-cell-ft-in-access {
		width: 7px;
		height: 7px;
		border-top: 1px solid #828282;
		border-right: 1px solid #828282;
		transform: rotate(45deg);
	}

	// 运费
	.transportation_expenses {
		background: #FFFFFF;
		border-radius: 9rpx;
		padding: 29rpx;
		margin-top: 20rpx;
		display: flex;
		justify-content: space-between;

		.tile {
			font-weight: 600;
			font-size: 25rpx;
		}

		.price {
			color: #FFDC28;
			font-weight: 600;
			font-size: 25rpx;
		}
	}

	.container {
		padding: 29rpx 29rpx 100px;

		.selected-all {
			display: flex;
			flex-direction: column;
			justify-content: center;
			width: 100%;
			background: #FFFFFF;
			border-radius: 9rpx;

			.drop-down-box {
				display: flex;
				align-items: center;
				justify-content: space-between;
				padding: 25rpx 29rpx;

				.dropdown-content {
					font-weight: 600;
					font-size: 29rpx;
					line-height: 40rpx;
					color: #FB7A26;
				}

				.dropdown-icon {
					width: 35rpx;
					height: 35rpx;

					&.select {
						transform: rotate(90deg);
					}
				}
			}

			.dialog-view {
				display: flex;
				flex-direction: column;
				justify-content: center;

				.dialog-title {
					font-size: 29rpx;
					border-top: 1rpx solid rgba(0, 0, 0, 0.1);
					padding: 20rpx 29rpx;
				}
			}
		}

		.store-list {
			background: #FFFFFF;
			border-radius: 9rpx;
			padding: 29rpx;
			margin-top: 20rpx;

			.title {
				margin-bottom: 29rpx;
				padding-bottom: 29rpx;
				border-bottom: 1rpx solid rgba(0, 0, 0, 0.1);
				font-weight: 600;
				font-size: 29rpx;
				line-height: 40rpx;
				color: #333333;
			}

			.column {
				margin-bottom: 29rpx;
				display: flex;

				.left {
					width: 102rpx;
					height: 102rpx;
					border-radius: 9rpx;
				}

				.center {
					flex: 1;
					margin: 0 29rpx;
					display: flex;
					flex-wrap: wrap;
					align-content: space-between;

					.name {
						width: 100%;
						font-weight: 600;
						font-size: 26rpx;
						line-height: 29rpx;
						color: #333333;
						display: -webkit-box;
						-webkit-box-orient: vertical;
						overflow: hidden;
						-webkit-line-clamp: 2;
					}

					.num {
						width: 100%;
						font-weight: 400;
						font-size: 22rpx;
						line-height: 29rpx;
						color: #979797;
					}
				}

				.right {
					font-weight: 600;
					font-size: 33rpx;
					line-height: 29rpx;
					color: #333333;

					text {
						font-size: 22rpx;
					}
				}
			}

			.price-total {
				display: flex;
				justify-content: space-between;
				align-items: center;
				border-top: 1px solid rgba(0, 0, 0, 0.1);
				padding-top: 29rpx;

				.tag {
					font-weight: 400;
					font-size: 25rpx;
					line-height: 29rpx;
				}

				.price {
					font-weight: 600;
					font-size: 33rpx;
					line-height: 29rpx;
					color: #333333;

					text {
						font-size: 22rpx;
					}
				}
			}
		}

		.remarks {
			background: #FFFFFF;
			border-radius: 9rpx;
			padding: 29rpx;
			margin-top: 20rpx;

			.title {
				font-weight: 400;
				font-size: 25rpx;
				line-height: 29rpx;
			}

			textarea {
				margin-top: 22rpx;
				width: 100%;
				min-height: 180rpx;
				background: #F9F9F9;
				border-radius: 9rpx;
				padding: 22rpx 29rpx;
				font-size: 22rpx;
				box-sizing: border-box;
			}
		}

		.btn-box {
			position: fixed;
			z-index: 999;
			display: flex;
			bottom: 15px;
			justify-content: center;
			align-items: center;
			margin: 0;
			height: 50px;
			width: calc(100% - 32px);

			&-left {
				height: 100%;
				flex: auto;
				display: flex;
				justify-content: flex-start;
				align-self: center;
				align-items: center;
				background: #222222;
				border-top-left-radius: 100upx;
				border-bottom-left-radius: 100upx;
				padding-left: 17rpx;

				.priceBox {
					flex: auto;
					margin-left: 22rpx;

					.hx-color-white {
						font-weight: 600;
						font-size: 33rpx;
						line-height: 29rpx;
						color: #fff;

						text {
							font-size: 22rpx;
						}
					}
				}

			}

			&-right {
				width: 170rpx;
				height: 100%;
				position: relative;
				display: flex;
				justify-content: flex-start;
				align-self: center;
				align-items: center;

				.jiesuan {
					width: 100%;
					height: 100%;
					font-size: 28upx;
					border-top-right-radius: 100upx;
					border-bottom-right-radius: 100upx;
					text-align: center;
					display: flex;
					justify-content: center;
					align-self: center;
					align-items: center;
					background: linear-gradient(45deg, #FFEB3B, #FFC107);
					font-weight: bold;
				}
			}
		}
	}
</style>